import string
import random
import logging
from yaml import safe_load
from os import path

# 文件路径
def dirname(filename='', filepath=''):
    return path.join(path.dirname(path.dirname(__file__)), filepath, filename)

# 随机输入n个字符串
def random_input(n):
    seq = string.ascii_letters + string.digits
    result = random.choices(seq, k=n)
    return ''.join(result)

# 记录日志信息
def log(context, name='log'):
    # 定义日志文件
    log_File = logging.FileHandler(dirname('log.txt', 'log'), 'a', encoding='utf-8')
    # 设置日志格式
    fmt = logging.Formatter('%(asctime)s-%(name)s:%(message)s')
    log_File.setFormatter(fmt)
    # 定义日志记录器
    logger = logging.Logger(name, logging.DEBUG)
    logger.addHandler(log_File)
    logger.info(context)
    log_File.close()

# 获取yaml数据
def readYaml(key, file=dirname('testdata.yaml', 'data')):
    with open(file, 'r', encoding='utf-8') as f:
        data = safe_load(f)
    if key in data:
        return data[key]
    else:
        log('文件数据不存在{}元素'.format(key))
        return None

if __name__ == '__main__':
    log('test', 'xxx')
    print(readYaml('passData'))
